package com.itheima.chapter06.polymorphic.test3;

//多态的好处与弊端&&&转型&&&存在风险 类型转换异常ClassCastException



public class Test {
    public static void main(String[] args) {
        useAimal(new Dog());//多态 向上转型 Animal a = new Dog();
        useAimal(new Cat());//多态 向上转型 Animal a = new Cat();
    }

    public static void useAimal(Animal a) {
        a.eat();
        //a.watchHome       父类中没有该方法，编译报错
        if(a instanceof Dog){       //无if则出现ClassCastException错误
            Dog dog =(Dog) a;//向下转型
            dog.watchHome();
        }
    }
}

abstract class Animal{
    public abstract void eat();
}
class Dog extends Animal{
    @Override
    public void eat() {
        System.out.println("狗吃肉");
    }
    public void watchHome(){
        System.out.println("看家");
    }
}
class Cat extends Animal{
    @Override
    public void eat() {
        System.out.println("猫吃鱼");
    }
}